<script lang="ts" setup>
import { useVbenDrawer } from '@vben/common-ui';
import { message } from 'ant-design-vue';
import { useVbenForm } from '#/adapter';
import { $t } from '#/locales';
import { watch, onMounted, nextTick, ref, computed } from 'vue';
import { getAllOptionListInTable } from '#/api/core/lowcode';
import type { Options } from '#/api/core/lowcode';
import { getOptionsApi } from '#/api/core/optiontool';

defineOptions({
  name: 'ModelDrawer',
});

const props = defineProps<{
  editData?: Record<string, any>;
  onSave?: (data: any) => boolean;
  tableName?: string;
  tableData?: { title: string; field: string; storage?: boolean; }[];
}>();

// 添加选项列表状态
const optionsList = ref<Options[]>([]);

// 添加获取选项列表的方法
async function fetchOptionsList() {
  if (props.tableName) {
    try {
      const data = await getAllOptionListInTable(props.tableName);
      optionsList.value = data;
    } catch (error) {
      console.error('获取选项列表失败:', error);
      message.error('获取选项列表失败');
    }
  }
}

// 添加默认值选项列表状态
const defaultValueOptions = ref<Options[]>([]);

// 添加获取默认值选项的方法
async function fetchDefaultValueOptions(value: string) {
  try {
    const data = await getOptionsApi({
      pathOrBeanName: value,
    });
    defaultValueOptions.value = data;
  } catch (error) {
    console.error('获取默认值选项失败:', error);
    message.error('获取默认值选项失败');
  }
}

// 添加计算属性来处理可选字段列表
const availableFields = computed(() => {
  if (!props.tableData) return [];
  // 编辑模式下排除当前字段
  const fieldsToExclude = props.editData ? [props.editData.field] : [];
  return props.tableData
    .filter(field =>
      // 排除当前字段
      !fieldsToExclude.includes(field.field) &&
      // 只包含storage为true或未定义的字段（默认为true）
      field.storage !== false
    )
    .map(field => ({
      label: field.title,
      value: field.field,
    }));
});

// 组件挂载时获取选项列表
onMounted(() => {
  fetchOptionsList();
  // 初始化影响字段和依赖字段的备选项
  if (props.editData?.component && ['Select', 'SelectMultiple', 'Radio', 'Checkbox'].includes(props.editData.component)) {
    formApi.setFieldValue('cascades', props.editData.cascades);
    formApi.setFieldValue('dependOn', props.editData.dependOn);
  }
});

// 使用 FormSchema 类型，并使用 show 属性来控制显示/隐藏
const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'Input',
      fieldName: 'field',
      label: '字段名',
      rules: 'required',
      componentProps: {
        placeholder: '请输入字段名',
      },
    },
    {
      component: 'Input',
      fieldName: 'title',
      label: '标题',
      rules: 'required',
      componentProps: {
        placeholder: '请输入标题',
      },
    },
    {
      component: 'Select',
      fieldName: 'component',
      label: '组件类型',
      rules: 'required',
      componentProps: {
        placeholder: '请选择组件类型',
        options: [
          { label: '输入框', value: 'Input' },
          { label: '多行文本', value: 'Textarea' },
          { label: '单项选择框', value: 'Select' },
          { label: '多项选择框', value: 'SelectMultiple' },
          { label: '单选按钮', value: 'Radio' },
          { label: '多选按钮', value: 'Checkbox' },
          { label: '日期选择', value: 'DatePicker' },
          { label: '时间选择', value: 'TimePicker' },
          { label: '日期时间选择', value: 'DateTimePicker' },
          { label: '数字输入', value: 'InputNumber' },
          { label: '密码输入', value: 'Password' },
          { label: '图片上传', value: 'ImageUpload' },
          { label: '文件上传', value: 'FileUpload' },
          { label: '图片预览', value: 'ImagePreview' },
          { label: '文件预览', value: 'FilePreview' },
        ],
      },
    },
    {
      component: 'Input',
      dependencies: {
        if(values) {
          // 输入类控件组
          return ['Input', 'Textarea'].includes(values.component);
        },
        triggerFields: ['component'],
      },
      fieldName: 'default',
      label: '默认值',
      componentProps: {
        placeholder: '请输入默认值',
      },
    },
    {
      component: 'Switch',
      fieldName: 'inTable',
      label: '表格列',
      defaultValue: true,
      componentProps: {
        style: 'width: auto',
      },
    },
    {
      component: 'Switch',
      fieldName: 'storage',
      label: '提交',
      defaultValue: true,
      componentProps: {
        style: 'width: auto',
      },
    },
    {
      component: 'Switch',
      fieldName: 'enable',
      label: '只读',
      componentProps: {
        style: 'width: auto',
      },
    },
    {
      component: 'Switch',
      fieldName: 'visible',
      label: '隐藏',
      defaultValue: false,
      componentProps: {
        style: 'width: auto',
      },
    },
    {
      component: 'Input',
      fieldName: 'helper',
      label: '帮助信息',
      componentProps: {
        placeholder: '请输入帮助信息',
      },
    },
    {
      component: 'RadioGroup',
      fieldName: 'width',
      label: '宽度',
      defaultValue: 'auto',
      componentProps: {
        options: [
          { label: '自动', value: 'auto' },
          { label: '自定义', value: 'custom' },
        ],
      },
    },
    {
      component: 'InputNumber',
      dependencies: {
        if(values) {
          return values.width === 'custom';
        },
        // 添加动态必填校验
        required(values) {
          return values.width === 'custom';
        },
        // 只有指定的字段改变时，才会触发
        triggerFields: ['width'],
      },
      fieldName: 'customWidth',
      label: '宽度值',
      componentProps: {
        placeholder: '请输入宽度值',
        style: 'margin-left: 8px',
      },
    },
    {
      component: 'Select',
      fieldName: 'rule',
      label: '校验规则',
      componentProps: {
        mode: 'multiple',
        placeholder: '请选择校验规则',
        options: [
          { label: '必填', value: 'required' },
          { label: '长度范围', value: 'length' },
          { label: 'IP格式', value: 'ip' },
          { label: '邮件格式', value: 'email' },
          { label: 'URL格式', value: 'url' },
          { label: '端口格式', value: 'port' },
          { label: '时间格式', value: 'date' },
          { label: '密码规则', value: 'password' },
        ],
      },
    },
    {
      component: 'InputNumber',
      dependencies: {
        if(values) {
          return values.rule?.includes('length');
        },
        // 添加动态必填校验
        required(values) {
          return values.rule?.includes('length');
        },
        triggerFields: ['rule'],
      },
      fieldName: 'ruleLength.min',
      label: '最小长度',
      componentProps: {
        placeholder: '请输入最小长度',
      },
    },
    {
      component: 'InputNumber',
      dependencies: {
        if(values) {
          return values.rule?.includes('length');
        },
        // 添加动态必填校验
        required(values) {
          return values.rule?.includes('length');
        },
        triggerFields: ['rule'],
      },
      fieldName: 'ruleLength.max',
      label: '最大长度',
      componentProps: {
        placeholder: '请输入最大长度',
      },
    },
    {
      component: 'Select',
      dependencies: {
        if(values) {
          return ['Select', 'SelectMultiple', 'Radio', 'Checkbox'].includes(values.component);
        },
        required(values) {
          return ['Select', 'SelectMultiple', 'Radio', 'Checkbox'].includes(values.component);
        },
        triggerFields: ['component'],
      },
      fieldName: 'source',
      label: '选项列表',
      componentProps: {
        placeholder: '请选择选项列表',
        options: optionsList,
        onSelect: (value: string) => {
          if (value) {
            formApi.setFieldValue('default', undefined);
            fetchDefaultValueOptions(value);
          } else {
            defaultValueOptions.value = [];
            formApi.setFieldValue('default', undefined);
          }
        },
      },
    },
    {
      component: 'Select',
      dependencies: {
        if(values) {
          return values.source && ['Select', 'SelectMultiple', 'Radio', 'Checkbox'].includes(values.component);
        },
        required(values) {
          return values.source && values.component === 'Radio';
        },
        triggerFields: ['component', 'source'],
      },
      fieldName: 'default',
      label: '默认值',
      componentProps: {
        placeholder: '请选择默认值',
        options: defaultValueOptions,
        allowClear: true,
      },
    },
    {
      component: 'Select',
      dependencies: {
        if(values) {
          return ['Select', 'SelectMultiple', 'Radio', 'Checkbox'].includes(values.component);
        },
        triggerFields: ['component'],
      },
      fieldName: 'cascades',
      label: '影响字段',
      help: '输入需要作为级联字段的条件字段名称',
      componentProps: {
        placeholder: '请选择影响字段',
        options: availableFields,
        allowClear: true,
      },
    },
    {
      component: 'Select',
      dependencies: {
        if(values) {
          return ['Select', 'SelectMultiple', 'Radio', 'Checkbox'].includes(values.component);
        },
        triggerFields: ['component'],
      },
      fieldName: 'dependOn',
      label: '依赖字段',
      help: '输入需要作为过滤条件的字段名称',
      componentProps: {
        placeholder: '请选择依赖字段',
        options: availableFields,
        allowClear: true,
      },
    },
    {
      component: 'Select',
      dependencies: {
        if(values) {
          return ['Select', 'SelectMultiple', 'Radio', 'Checkbox'].includes(values.component);
        },
        triggerFields: ['component'],
      },
      fieldName: 'options',
      label: '选项配置',
      componentProps: {
        placeholder: '请选择选项配置',
      },
    },
  ],
  showDefaultActions: false});

// 设置表单数据的函数
async function setFormData(data?: Record<string, any>) {
  if (!data) {
    await formApi.resetForm();
    return;
  }

  try {
    // 等待下一个 tick，确保表单已经渲染
    await nextTick();

    // 先重置表单
    await formApi.resetForm();

    // 逐个设置字段值
    for (const [key, value] of Object.entries(data)) {
      if (value !== undefined) {
        await formApi.setFieldValue(key, value);
      }
    }

    // 验证设置是否成功
    const currentValues = await formApi.getValues();
    console.log('Current form values:', currentValues);
  } catch (error) {
    console.error('Error setting form data:', error);
  }
}

// 修改 watch 函数
watch(
  () => props.editData,
  async (newVal) => {
    if (newVal) {
      // 将 Proxy 对象转换为普通对象
      const plainData = JSON.parse(JSON.stringify(newVal));
      console.log('Setting edit data:', plainData);
      await setFormData(plainData);
      // 如果是选项类控件且有source，初始化默认值选项
      if (
        ['Select', 'SelectMultiple', 'Radio', 'Checkbox'].includes(plainData.component) &&
        plainData.source
      ) {
        await fetchDefaultValueOptions(plainData.source);
      }
    } else {
      await formApi.resetForm();
    }
  },
  { immediate: true }
);

// 修改 onSubmit 函数
async function onSubmit(values: Record<string, any>) {
  try {
    const validResult = await formApi.validate();
    if (!validResult.valid) {
      message.error($t('common.form.required'));
      return;
    }

    if (props.onSave) {
      const saveResult = props.onSave(values);
      if (saveResult === true) {
        drawerApi.close();
      }
    } else {
      throw new Error('Save callback not provided');
    }
  } catch (error: any) {
    message.error(error.message || $t('common.submit.failed'));
  }
}

// 修改 Drawer 的配置
const [Drawer, drawerApi] = useVbenDrawer({
  onCancel() {
    formApi.resetForm();
    drawerApi.close();
  },
  onConfirm: async () => {
    try {
      // 调用 submitForm 并等待结果
      await formApi.submitForm();
      // 不直接返回 submitForm 的结果
      return true;
    } catch (error: any) {
      console.error('提交失败:', error);
      message.error(error.message || $t('common.submit.failed'));
      return false;
    }
  },
});

onMounted(async () => {
  // 等待表单初始化
  await nextTick();
  if (props.editData) {
    const plainData = JSON.parse(JSON.stringify(props.editData));
    await setFormData(plainData);
  }
});
</script>

<template>
  <Drawer :title="props.editData ? '编辑' : '新增'">
    <Form />
  </Drawer>
</template>

<style lang="less" scoped>
:deep(.ant-form) {
  width: 100%;
  padding: 16px 24px;

  .ant-form-item {
    margin-bottom: 16px;
    display: flex;

    .ant-form-item-label {
      width: 120px;
      flex-shrink: 0;

      > label {
        justify-content: flex-end;
        width: 100%;
        text-align: right;
      }
    }

    .ant-form-item-control {
      flex: 1;
      padding-left: 12px;
      min-width: 0;

      .ant-input,
      .ant-input-number,
      .ant-select,
      .ant-radio-group,
      .ant-checkbox-group,
      .ant-switch {
        text-align: left;
      }

      .ant-switch {
        width: 44px;
      }
    }
  }

  .ant-select-selection-item {
    text-align: left;
  }

  .ant-form-item-group {
    display: flex;
    align-items: center;
    gap: 8px;

    .ant-radio-group {
      margin-right: 8px;
    }

    .ant-input-number {
      width: 120px;
    }
  }
}
</style>
